package cn.hj.order.service.impl;


import cn.hj.basic.constant.PayConstant;
import cn.hj.basic.service.impl.BaseServiceImpl;
import cn.hj.basic.util.CodeGenerateUtils;
import cn.hj.basic.util.DistanceUtil;
import cn.hj.order.domain.AdoptOrder;
import cn.hj.order.domain.OrderAddress;
import cn.hj.order.domain.ProductOrder;
import cn.hj.order.domain.ProductOrderDetail;
import cn.hj.order.mapper.OrderAddressMapper;
import cn.hj.order.mapper.ProductOrderDetailMapper;
import cn.hj.order.mapper.ProductOrderMapper;
import cn.hj.order.service.IProductOrderService;
import cn.hj.org.domain.Shop;
import cn.hj.org.mapper.ShopMapper;
import cn.hj.pay.domain.PayBill;
import cn.hj.pay.mapper.PayBillMapper;
import cn.hj.pay.service.IPayBillService;
import cn.hj.product.domain.Product;
import cn.hj.product.mapper.ProductMapper;
import cn.hj.product.service.IProductService;
import cn.hj.user.domain.Logininfo;
import cn.hj.user.domain.User;
import cn.hj.user.domain.UserAddress;
import cn.hj.user.mapper.UserAddressMapper;
import cn.hj.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

@Service
public class ProductOrderServiceImpl extends BaseServiceImpl<ProductOrder> implements IProductOrderService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private ProductOrderMapper productOrderMapper;

    @Autowired
    private ProductOrderDetailMapper productOrderDetailMapper;

    @Autowired
    private OrderAddressMapper orderAddressMapper;

    @Autowired
    private PayBillMapper payBillMapper;

    @Autowired
    private IPayBillService payBillService;

    @Autowired
    private IProductService productService;


    @Override
    @Transactional
    public String submit(Map<String, Object> params,Logininfo logininfo) {
        Long productId = Long.valueOf(params.get("product_id").toString());//服务ID
        Integer productNum = Integer.valueOf(params.get("product_num").toString());//服务数量
        Long addressId = Long.valueOf(params.get("address_id").toString());//地址id
        Long payMethod = Long.valueOf(params.get("pay_method").toString());//支付方式
        //1.创建订单
        Product product = productMapper.selectById(productId);
        if(product.getSalecount()==null){
            product.setSalecount(Long.valueOf(productNum));
        }else {
            product.setSalecount(product.getSalecount()+productNum);
        }
        productService.update(product);
        User user = userMapper.getByLogInfoId(logininfo.getId());
        UserAddress userAddress = userAddressMapper.selectById(addressId);
        ProductOrder order = initProductOrder(productNum, product, user, userAddress);
        productOrderMapper.insert(order);
        //2.订单详情  防止服务价格变更
        ProductOrderDetail detail = new ProductOrderDetail();
        BeanUtils.copyProperties(product,detail);
        detail.setId(null);
        detail.setOrder_id(order.getId());
        detail.setProduct_id(String.valueOf(productId));
        productOrderDetailMapper.insert(detail);
        //3.订单地址
        OrderAddress orderAddress = userAddress2OrderAddress(userAddress,order);
        orderAddressMapper.insert(orderAddress);
        // 生成支付单并支付
        PayBill payBill = initPayBill(payMethod, user, order);
        //@TODO 支付超时定时器
        payBillMapper.insert(payBill);
        return payBillService.pay(payBill);
    }


    private PayBill initPayBill(Long payMethod, User user, ProductOrder order) {
        PayBill payBill = new PayBill();
        payBill.setDigest("[摘要]对"+order.getOrderSn()+"支付订单！");
        payBill.setMoney(order.getPrice());
        payBill.setUnionPaySn(order.getPaySn());
        //不设置状态默认有
        payBill.setLastPayTime(order.getLastPayTime());
        payBill.setPayChannel(payMethod); //0  支付宝 1 微信 2 银联
        payBill.setBusinessType(PayConstant.SERVICE_ORDER );
        payBill.setBusinessKey(order.getId());
        payBill.setNickName(user.getUsername());
        payBill.setUser_id(order.getUser_id());
        payBill.setShop_id(order.getShop_id());
        return payBill;
    }
    /**
     * 生成订单地址
     * @param userAddress
     * @param order
     * @return
     */
    public OrderAddress userAddress2OrderAddress(UserAddress userAddress, ProductOrder order){
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(userAddress,orderAddress);
        orderAddress.setOrder_id(order.getId());
        orderAddress.setOrderSn(order.getOrderSn());
        orderAddress.setCreateTime(new Date());
        return orderAddress;
    }

    private ProductOrder initProductOrder(Integer productNum, Product product, User user, UserAddress userAddress) {
        ProductOrder order = new ProductOrder();
        order.setDigest("[摘要]服务"+product.getName()+"订单！");
        order.setState(0);//待支付
        order.setPrice(product.getSaleprice().multiply(new BigDecimal(productNum)));//价格=服务单价*数量
        String orderSn = CodeGenerateUtils.generateOrderSn(user.getId());
        order.setOrderSn(orderSn);
        order.setLastPayTime(new Date(System.currentTimeMillis() + 15*60*1000));//最终支付时间
        //order.setLastConfirmTime();//
        order.setPaySn(CodeGenerateUtils.generateUnionPaySn());
        order.setProduct_id(product.getId());
        order.setUser_id(user.getId());
        //我们需要分配最近的店铺
        Shop nearestShop = DistanceUtil.getNearestShop(DistanceUtil.getPoint(userAddress.getFullAddress()), shopMapper.selectAll());
        if(nearestShop!=null){
            order.setShop_id(nearestShop.getId());
        }
        return order;
    }

}
